package book;

import java.time.LocalDate;

public class BookDaoImpl implements BookDao{

	private Book[] books;
	private int index;
	
	public BookDaoImpl(){
		books = new Book[10];
	}
	
	public BookDaoImpl(int size){
		books = new Book[size];
	}
	
	
	@Override
	public int insert(Book book) {
		if (index >= books.length) {
			return 0;
		} else {
			books[index] = book;
			index++;
			return 1;
		}
	}

	@Override
	public int update(Book book) {
		for(int i = 0 ; i < books.length; i++) {
			if (books[i].getBookId() == book.getBookId()) {
				books[i] = book;
				return 1;
			}
		}
		return 0;
	}

	@Override
	public int rent(int bookId) {
		for(int i = 0 ; i < index; i++) {
			// 根据bookId循环找书，并且这本书如果找到必须是没被借出去
			if (books[i].getBookId() == bookId && books[i].isRent()==false) {
				//已经借出去了
				books[i].setRent(true);
				//次数++
				int time = books[i].getRentTime() + 1;
				books[i].setRentTime(time);
				//设置借出去的时间
				books[i].setRentDate(LocalDate.now());
				return 1;
			}
		}
		return 0;
	}

	@Override
	public int back(int bookId) {
		for(int i = 0 ; i < index; i++) {
			// 根据bookId循环找书，并且这本书如果找到必须是没被借出去
			if (books[i].getBookId() == bookId && books[i].isRent()==true) {
				//已经还回来
				books[i].setRent(false);
				//不设置借出时间
				books[i].setRentDate(null);
				return 1;
			}
		}
		return 0;
	}

	@Override
	public Book selectById(int bookId) {
		for(int i = 0 ; i < index; i++) {
			if (books[i].getBookId() == bookId) {
				return books[i];
			}
		}
		return null;
	}

	@Override
	public Book[] selectAll() {
		Book[] copy = new Book[index];
		System.arraycopy(books, 0, copy, 0, index);
		return copy;
	}

	@Override
	public Book[] sortByRentTime() {
		Book[] copy = new Book[index];
		System.arraycopy(books, 0, copy, 0, index);
		
		for (int j = 0; j < index; j++) {
			for (int i = 0; i < index - 1; i++) {
				if (copy[i].getRentTime() < copy[i+1].getRentTime()) {
					Book t = copy[i];
					copy[i] = copy[i+1];
					copy[i+1] = t;
				}
			} 
		}
		return copy;
	}

}
